package com.takepoints.mobile;

import java.io.IOException;
import java.util.List;

import com.takepoints.android.TPConst;
import com.takepoints.android.vo.TakeReturn;
import com.takepoints.android.bo.Promotion;
import com.takepoints.android.services.PublicServices;
import com.takepoints.android.services.TPServices;
import com.takepoints.android.util.SecurityUtil;
import com.takepoints.android.util.StringUtil;

import android.annotation.TargetApi;
import android.app.AlertDialog;
import android.app.PendingIntent;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.IntentFilter.MalformedMimeTypeException;
import android.media.Ringtone;
import android.media.RingtoneManager;
import android.net.Uri;
import android.nfc.FormatException;
import android.nfc.NfcAdapter;
import android.nfc.Tag;
import android.nfc.tech.MifareClassic;
import android.nfc.tech.NfcA;
import android.os.AsyncTask;
import android.os.Bundle;

@TargetApi(10)
public class TakeIt extends BaseActivity {
	
	private static NfcAdapter mAdapter;
	private static PendingIntent mPendingIntent;
	private static IntentFilter[] mFilters;
	private static String[][] mTechLists;
	
	@Override
    public void onCreate(Bundle savedInstanceState){
        super.onCreate(savedInstanceState);
        setContentView(R.layout.verifycodenfc);
        manageMenu(5);
        
        mAdapter = NfcAdapter.getDefaultAdapter(this);
		mPendingIntent = PendingIntent.getActivity( this, 0
								, new Intent(this , getClass()).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP)
								, 0);
		
		IntentFilter ndef = new IntentFilter(NfcAdapter.ACTION_TECH_DISCOVERED);
		try{
			ndef.addDataType("*/*");
		} catch(MalformedMimeTypeException e){
			alert("MalformedMimeTypeException : " + e.getMessage());
		}

		mFilters = new IntentFilter[] { ndef, };
		mTechLists = new String[][] {
				new String[] { MifareClassic.class.getName(), NfcA.class.getName() }
		};
	}
	
	private void resolveIntent(Intent intent){
		String action = intent.getAction();
		if(NfcAdapter.ACTION_TECH_DISCOVERED.equals(action)) {
			Tag tagFromIntent = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
			if(tagFromIntent != null){
				try {
					/*
					Uri notification = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
					Ringtone r = RingtoneManager.getRingtone(getApplicationContext(), notification);
					r.play();
					*/
					String encryptedCode = read(tagFromIntent);
					new VerifyCodeProcess(this).execute(encryptedCode);
					
				} catch(Exception e){
					popup("เกิดความผิดพลาด :\n\n" + e.getMessage());
				}
			}
		}
	}
	
	private String read(Tag tag) throws IOException, FormatException {
		StringBuilder result = new StringBuilder("");
		if(tag != null){
			MifareClassic mfc = MifareClassic.get(tag);
    		if(!mfc.isConnected()) mfc.connect();
    		boolean auth = mfc.authenticateSectorWithKeyA(1, SecurityUtil.getAuthenKey());
    		if(auth){
    			int bCount = mfc.getBlockCountInSector(1);
                int bIndex = 0;
                for(int i=0; i<bCount-1; i++){
                	bIndex = mfc.sectorToBlock(1);
                	if(!mfc.isConnected()) mfc.connect();
                    byte[] data = mfc.readBlock(bIndex + i);
                    
                    result.append(new String(data));
                }
    		} else{
    			popup("เกิดความผิดพลาด :\n\nไม่สามารถทำรายการได้ !");
    		}
    		mfc.close();
		}
		return result.toString();
    }
	
	@Override
	public void onNewIntent(Intent intent){
    	super.onNewIntent(intent);
		resolveIntent(intent);
	}
	
	@Override
	public void onResume(){
		super.onResume();
		if(mAdapter != null){
			mAdapter.enableForegroundDispatch(this, mPendingIntent, mFilters, mTechLists);
		}
	}

	@Override
	public void onPause(){
		super.onPause();
        if(mAdapter != null){
            mAdapter.disableForegroundDispatch(this);
        }
	}
	
	@Override
	public void onBackPressed(){
		backToHome();
		return;
	}
	
	protected void processTake(Context ctx){
		Intent homeInt = new Intent(this, Takepoints.class);
		startActivity(homeInt);
		finish();
	}
	
	private void alertResult(String msg, final TakeReturn tr){
		final AlertDialog.Builder alertbox = new AlertDialog.Builder(this);
		alertbox.setMessage(msg);
		alertbox.setPositiveButton("OK", new DialogInterface.OnClickListener(){
			public void onClick(DialogInterface dlgInf, int which){
				if(tr != null){
					gotoCardDetail(tr);
				} else{
					backToHome();
				}
			}
		});
		alertbox.show();
	}
	private void gotoCardDetail(TakeReturn tr){
		Intent intent = null;
		if(PublicServices.PROMOTION_TYPE_CARD == tr.getPromoTypeId()){
			intent = new Intent(this, MyCardDetail.class);
			intent.putExtra("cardId", tr.getOfferId());
			intent.putExtra("siteName", tr.getSiteName());
			intent.putExtra("takeNow", "Y");
			
		} else if(PublicServices.PROMOTION_TYPE_OFFER == tr.getPromoTypeId()){
			intent = new Intent(this, MyOfferDetail.class);
			intent.putExtra("cardId", tr.getOfferId());
			intent.putExtra("siteName", tr.getSiteName());
			intent.putExtra("takeNow", "Y");
			
		} else if(PublicServices.PROMOTION_TYPE_REWARD == tr.getPromoTypeId()){
			intent = new Intent(this, MyRewardDetail.class);
			intent.putExtra("cardId", tr.getOfferId());
		}
		if(intent != null){
			startActivity(intent);
			finish();
		} else{
			backToHome();
		}
    }
	private void backToHome(){
		Intent homeInt = new Intent(this, Takepoints.class);
		startActivity(homeInt);
		finish();
    }
	
	class VerifyCodeProcess extends AsyncTask<String, Void, TakeReturn>{
		
		private Context context = null;
		private ProgressDialog progressDlg = null;
		
		VerifyCodeProcess(Context context){
			this.context = context;
		}
		
		@Override
        protected void onPreExecute(){
            super.onPreExecute();
            progressDlg = ProgressDialog.show(context, "Takepoints.com", "Taking ...", true);
		}
		
		@Override
        protected TakeReturn doInBackground(String... params){
			String encryptedCode = params[0];
			TakeReturn tr = new TakeReturn();
			tr.setPromotionSize(-1);
			try{
				String nfcId = SecurityUtil.decrypt(encryptedCode, SecurityUtil.KEY_TYPE_PRIVATE);
				List<Promotion> promoL = PublicServices.getSitePromoListByNfcId(nfcId);
				if(promoL != null){
					if(promoL.size() == 1){
						Promotion promo = promoL.get(0);
						if( promo != null ){
							String pid = promo.getPromotionId();
							
							// has only 1 promo, call TakeNow function
							tr = PublicServices.takeNow( getSharedIntValue(TPConst.PRF_MEMBER_ID)
													   				, pid, nfcId );
							tr.setSiteName(promo.getCustomerName() + " (" + promo.getSiteName() + ")");
							tr.setPromoTypeId(Integer.parseInt(StringUtil.nvl(promo.getPromoTypeId(), "0")));
							
							// Find offer id from promo id
							String oid = TPServices.getOfferFromPromo(pid, tr.getMemberId());
							tr.setOfferId(oid);
						}
					}
					tr.setPromotionSize(promoL.size());
				} else{
					tr.setPromotionSize(0);
				}
				tr.setNfcId(nfcId);
			} catch(Exception e){
				tr.setMessage(e.getMessage());
			}
			return tr;
		}
		
		@Override
        protected void onPostExecute(TakeReturn tr){
        	progressDlg.dismiss();
        	if(tr != null && !StringUtil.isEmpty(tr.getTrxCode())){
        		
        		String strPromoType = "คุณใช้ที่\n";
        		if(PublicServices.PROMOTION_TYPE_CARD == tr.getPromoTypeId()){
        			strPromoType = "คุณใช้บัตรสะสมที่ \n";
        		} else if(PublicServices.PROMOTION_TYPE_OFFER == tr.getPromoTypeId()){
        			strPromoType = "คุณใช้คูปองส่วนลดที่\n";
        		} else if(PublicServices.PROMOTION_TYPE_DEAL == tr.getPromoTypeId()){
        			strPromoType = "คุณใช้ดีลที่\n";
        		}
        		alertResult( "กรุณาแสดงรหัสให้พนักงาน : " + tr.getTrxCode()
       				 	 //+ (!StringUtil.isEmpty(tr.getTrxDesc())?"\n\n(" + tr.getTrxDesc() + ")":""), tr );
        				+ "\n\n" + strPromoType + tr.getSiteName(), tr);
        		
			} else if(tr != null && tr.getPromotionSize() > 1){
				goToPromotionList(tr.getNfcId());
				
			} else if(tr != null && !StringUtil.isEmpty(tr.getMessage())){
				alertResult(tr.getMessage(), null);
				
			} else{
				alertResult("ไม่พบโปรโมชั่น ณ ร้านค้านี้ !", null);
			}
		}
		
	}
	
	private void goToPromotionList(String nfcId){
		Intent intent = new Intent(this, TPPromotions.class);
		intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP);
		intent.putExtra("nfcId", nfcId);
		startActivity(intent);
    }
	
}
